package com.zzsy.carosshopprojects.activitys.home.mainpage.common;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.king.base.util.ToastUtils;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.activitys.home.mainpage.common.scan.ScanOnlyAc;
import com.zzsy.carosshopprojects.adapter.PayKindAdapter;
import com.zzsy.carosshopprojects.base.BaseActivity;
import com.zzsy.carosshopprojects.base.BaseFragment;
import com.zzsy.carosshopprojects.base.ConfigureFile;
import com.zzsy.carosshopprojects.bean.MessageEvent;
import com.zzsy.carosshopprojects.util.Cons;
import com.zzsy.carosshopprojects.util.HUD;
import com.zzsy.carosshopprojects.util.Util;
import com.zzsy.carosshopprojects.util.ViewBgUtil;
import com.zzsy.carosshopprojects.view.MyGridView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindDimen;
import butterknife.BindView;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 收款页面
 */
public class CollectionFragment extends BaseFragment implements AdapterView.OnItemClickListener {
    public static CollectionFragment newInstance(String amount, String usedOil, String productId, String oilsPrice, String productInfoId) {
        CollectionFragment collectionFragment = new CollectionFragment();
        Bundle bundle = new Bundle();
        bundle.putString("amount", amount);
        bundle.putString("usedOil", usedOil);
        bundle.putString("productId", productId);
        bundle.putString("oilsPrice", oilsPrice);
        bundle.putString("productInfoId", productInfoId);
        collectionFragment.setArguments(bundle);
        return collectionFragment;
    }

    @BindView(R.id.recycleView)
    MyGridView recycleView;
    @BindView(R.id.ly_main)
    LinearLayout ly_main;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_oils_num)
    TextView tv_oils_num;
    private PayKindAdapter payKindAdapter;
    private CollectionMode collectionMode;
    @BindDimen(R.dimen.p_25)
    int p_20;
    private String[] permissionArrs = {Manifest.permission.CAMERA};
    private boolean isClickBank = true;
    private boolean isFirstBnakPay = true;

    @Override
    protected int initLayout() {
        return R.layout.fg_collection;
    }

    @Override
    protected void initView(View view) {
        initTitle(view, getResources().getString(R.string.Collection), getActivity());
        ly_main.setBackground(ViewBgUtil.setBg(15, Color.parseColor(ConfigureFile.ColorWhite)));

    }

    @Override
    protected void initData(Context mContext) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        collectionMode = getViewModelProvider().get(CollectionMode.class);
        payKindAdapter = new PayKindAdapter(getContext(), null, 0);
        recycleView.setAdapter(payKindAdapter);
        recycleView.setOnItemClickListener(this);
        tv_oils_num.setText(getArguments().getString("usedOil"));
        tv_money.setText("￥" + getArguments().getString("amount"));
    }

    @Override
    protected void loadMethod() {
        showListData();
        orderResult();
    }

    /**
     * 展示支付方式的数据
     */
    private void showListData() {
        collectionMode.getLiveData().observe(this, beans -> {
            payKindAdapter.setListData(beans);
            payKindAdapter.notifyDataSetChanged();
        });
        collectionMode.setPayData();
    }

    /**
     * 支付订单结果
     */
    private void orderResult() {
        collectionMode.getLiveOrderData().observe(this, orderResultBean -> {
            Log.d("xxxxxx", "666455656688");
            if (orderResultBean == null) {
                getActivity().finish();
            } else {
                Scanner(orderResultBean.getType(), orderResultBean.getPayAmount(), orderResultBean.getOrderNumber());
            }

        });
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//        if (ThrottleFirstUtil.isFastClick()) {
//            return;
//        }
        switch (payKindAdapter.getListData().get(i).getType()) {
            case PayKindAdapter.ZFB:
                toPay("1");
                break;
            case PayKindAdapter.WX:
                toPay("2");
                break;
            case PayKindAdapter.YL:
                if (isClickBank) {
                    isClickBank = false;
                    toPay("3");
                } else {

                }

                break;
        }
    }

    private void toPay(String type) {
        collectionMode.toPay(getContext(), type, getArguments().getString("amount"), getArguments().getString("productId"), getArguments().getString("productInfoId"), getArguments().getString("usedOil"), getArguments().getString("oilsPrice"));
    }

    /**
     * 进行扫描数据 通过微信支付宝支付
     */
    private void Scanner(String payType, String payAmount, String orderNumber) {
        if (EasyPermissions.hasPermissions(getActivity(), permissionArrs)) {
            if (payType.equals(ConfigureFile.CARDPAY)) {
                bankCardPay(payAmount, orderNumber);
            } else {
                ScanOnlyAc.start(getContext(), "5", payAmount, payType, orderNumber);
                getActivity().finish();
            }

        } else {
            EasyPermissions.requestPermissions(getActivity(), getResources().getString(R.string.get_photo_permission_tip), 0x11, permissionArrs);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        switch (event.message) {
            case MessageEvent.ACTIVITYCLOSE:
                getActivity().finish();
                break;
        }
    }

    /**
     * 银行卡支付
     */
    private void bankCardPay(String payAmount, String orderNumber) {
        Log.d("xxxxxx", "6664556566");
        if (!isFirstBnakPay) {
            return;
        }
        isFirstBnakPay = false;
        HUD.getInstance().show(getContext(), "跳转中...");
        ComponentName component = new ComponentName("com.fuyousf.android.fuious", "com.fuyousf.android.fuious.MainActivity");
        Intent intent = new Intent();
        intent.setComponent(component);
        Bundle bundle = new Bundle();
        try {
            bundle.putString("transName", "消费");
            long m = Long.parseLong(String.valueOf(payAmount));
            bundle.putString("amount", String.format("%012d", m));
            bundle.putString("orderNumber", orderNumber);
            bundle.putString("isPrintTicket", "false");
            bundle.putString("version", Cons.version);
        } catch (Exception e) {
            HUD.getInstance().dismiss();
            ToastUtils.showToast(getContext().getApplicationContext(), getResources().getString(R.string.payAccountError));
            getActivity().finish();
            return;
        }
        if (Util.isIntentExisting(intent, getContext())) {
            intent.putExtras(bundle);
            getActivity().startActivityForResult(intent, BaseActivity.REQUEST_CODE);
        } else {
            HUD.getInstance().dismiss();
            getActivity().finish();
            ToastUtils.showToast(getContext().getApplicationContext(), getResources().getString(R.string.L3));
        }
    }
}
